﻿using System.Threading;
using System.Timers;
using System.Windows;

namespace WpfApp.Uers
{
    public class AuthTimeoutEventArgs : EventArgs
    {
        public int TimeCount { get; set; }
    }

    public static class GlobalIdentity
    {
        public static bool IsAuth => CurrentUser != null;

        private static User? CurrentUser { get; set; }

        public static event EventHandler<AuthTimeoutEventArgs>? ElapsedAsync;

        public static event EventHandler? UnregisteredAsync;

        private readonly static System.Timers.Timer Timer;

        private static int TimeCount { get; set; } = 180; // 3min

        private static int _flag = 0;  // 0=false, 1=true

        private static bool IsStop
        {
            get => Interlocked.CompareExchange(ref _flag, 0, 0) == 1;
            set => Interlocked.Exchange(ref _flag, value ? 1 : 0);
        }

        static GlobalIdentity()
        {
            Timer = new System.Timers.Timer(TimeSpan.FromSeconds(1));
            Timer.Elapsed += OnTimerElapsed;
        }

        private static void OnTimerElapsed(object? sender, ElapsedEventArgs e)
        {
            if (!IsStop)
            {
                ElapsedAsync?.Invoke(CurrentUser, new AuthTimeoutEventArgs() { TimeCount = GlobalIdentity.TimeCount });
                GlobalIdentity.TimeCount--;

                if (GlobalIdentity.TimeCount < 0)
                {
                    UnregisteredAsync?.Invoke(CurrentUser, EventArgs.Empty);
                    CurrentUser = null;
                    GlobalIdentity.CleanAuth();
                }
            }
        }

        public static void SetAuth(User user)
        {
            TimeCount = 180;
            IsStop = false;
            CurrentUser = user;
            Timer.Start();
        }

        public static User? GetCurrentUser()
        {
            return CurrentUser;
        }

        public static void CleanAuth()
        {
            IsStop = true;
            CurrentUser = null;
            Timer.Stop();
        }
    }
}
